#!/usr/bin/env bash

set -e

base_path=$(pwd)
ops_global_path="${base_path%%/Documents/*}/Documents/ops/ops_global.properties"
clone_config_file="$base_path/ops.properties"
log_file="$base_path/kp.log"

# 日志函数
log() {
    local message=$1
    echo "$(date +'%Y-%m-%d %H:%M:%S') - $message" | tee -a "$log_file" >&2
}

# 配置读取函数
read_config() {
    local key=$1
    value=$(grep -E "^$key=" "$clone_config_file" | sed -E "s/^$key=//")
    echo "$value"
}
# 配置读取函数
read_global_config() {
    local key=$1
    value=$(grep -E "^$key=" "$ops_global_path" | sed -E "s/^$key=//")
    echo "$value"
}
# 写入配置的函数
write_config() {
    local key=$1
    local value=$2
    # 对 value 进行转义，避免特殊字符引发 sed 替换失败
    local escaped_value
    escaped_value=$(echo "$value" | sed 's/[&/\]/\\&/g')
    # 如果 key 已存在，替换它的值；否则追加新的 key=value
    if grep -q "^$key=" "$clone_config_file"; then
        # 替换已存在的键值对
        sed -i '' "s/^$key=.*/$key=$escaped_value/" "$clone_config_file"
    else
        # 追加新的键值对
        echo "$key=$value" >> "$clone_config_file"
    fi
}

# 帮助信息
show_help() {
    echo "Usage:"
    echo "  kp                 # 默认：构建并运行"
    echo "  kp -b 'A1,B1'      # 构建指定项目,打出精简包，然后放入基座中，然后打包基座，输出最终的基座 jar"
    echo "  kp -b              # 构建当前目录所有项目"
    echo "  kp -r              # 启动 基座 jar 包"
    echo "  kp -br 'A1,B1'     # 构建指定项目,打出精简包，然后放入基座中，然后打包基座，输出最终的基座 jar,最终运行基座jar"
}

# 构建函数
build_projects() {
    local args=("$@")
    local total=${#args[@]}
    ops_user=$(read_global_config "ops_user")
    mvn_setting=$(read_global_config  "mvn_setting")
    # 最后一个是 parent_dir 就是应用的上一级文件夹，也就是app 这个值
    local parent_dir="${args[$((total - 1))]}"
    # 倒数第二个是 jz_project_path 基座的项目目录
    local jz_project_path="${args[$((total - 2))]}"
    # 最后一个是 parent_dir
    local projects=("${args[@]:0:$((total - 2))}")
    # 对应项目下的
    local output_dir="$base_path/$parent_dir/jar"
    mkdir -p "$output_dir"
    mkdir -p "$jz_project_path/hs_koupleless"
    rm -rf "$jz_project_path/hs_koupleless"/*
    rm -rf "$base_path/$parent_dir/jar"/*
    log "✅ 已清空目录：$jz_project_path/hs_koupleless | $base_path/$parent_dir/jar"
    # shellcheck disable=SC2128
    # 先打包项目
    for project_path in "${projects[@]}"; do
        father_path=$(read_config "project.plugin.$project_path.father")
        if [ -n "${father_path}" ]; then
            log "存在 父项目，拼接字符处理: $father_path"
            project_path="$father_path/$project_path"
        fi
        log "🔧 打包 改造 项目：$project_path"
        log "项目构建指令：$mvn_setting -Dmaven.multiModuleProjectDirectory="$base_path/$parent_dir/$project_path"  clean package -DskipTests -P 'mas-fabudan,vb-fabudan,!daily,!vb-daily' -f $base_path/$parent_dir/$project_path/pom.xml -T 4C"
        $mvn_setting -Dmaven.multiModuleProjectDirectory="$base_path/$parent_dir/$project_path"  clean package -DskipTests  -P 'mas-fabudan,vb-fabudan,!daily,!vb-daily'  -f $base_path/$parent_dir/$project_path/pom.xml -T 4C
        ark_jar=$(find "$base_path/$parent_dir/$project_path/target" -type f -name "*ark-biz.jar" | head -n 1)
        if [[ -z "$ark_jar" ]]; then
            log "❌ 未找到 $project_path 的 jar 包，终止"
            exit 1
        fi
        # 放入对应基座的地址中
        cp "$ark_jar" "$output_dir"
        cp "$ark_jar" "$jz_project_path/hs_koupleless"
    done
    # 基座对应的目录
    log "📂 当前 $jz_project_path/hs_koupleless 目录下文件："
    ls -l "$jz_project_path/hs_koupleless"
    log "🔧 开始打包 基座项目 项目：$jz_project_path"
    # 打包基座。指定路径
    log "基座构建指令：-Dmaven.multiModuleProjectDirectory="$jz_project_path"  clean package -DskipTests package -P 'mas-fabudan,vb-fabudan,!daily,!vb-daily'  -f $jz_project_path/pom.xml -DintegrateLocalDirs='$output_dir' -T 4C"
    pushd "$jz_project_path" > /dev/null
      $mvn_setting -Dmaven.multiModuleProjectDirectory="$jz_project_path"  clean package -DskipTests package -P 'mas-fabudan,vb-fabudan,!daily,!vb-daily'  -f $jz_project_path/pom.xml -DintegrateLocalDirs='$output_dir' -T 4C
      jz_jar=$(find "$jz_project_path/target" -type f -name "*.jar" ! -name "*sources.jar" | head -n 1)
    popd > /dev/null
    if [[ -z "$ark_jar" ]]; then
        log "❌ 未找到 基座.jar，终止执行"
        exit 1
    fi
    # shellcheck disable=SC21
    # 加个 jz 前缀
    cp "$jz_jar" "$base_path/$parent_dir/jar/jz_$(basename "$jz_jar")"
    # 基座运行地址放入
    write_config "project.plugin.jz.run.jar.path" "$base_path/$parent_dir/jar/jz_$(basename "$jz_jar")"
    write_config "project.plugin.jz.run.path" "$base_path/$parent_dir"
    log "✅ 构建完成"
}

# 启动函数：不再接收项目参数
run_projects() {
    jdk_setting=$(read_global_config  "jdk_setting")
    log "jdk设置路径：$jdk_setting"
    jz_jar_path=$(read_config "project.plugin.jz.run.jar.path")
    jz_path=$(read_config "project.plugin.jz.run.path")
    if [[ ! -f "$jz_jar_path" ]]; then
      log "❌ 基座jar 不存在 请先打包"
      exit 1
    fi
    kill -9 $(lsof -ti :8080 2>/dev/null) 2>/dev/null || true
    log "🚀 启动基座 $jz_jar_path  jar 包"
    rm -rf "$jz_path/log"/*
    log "✅ 已清空目录：$jz_path/log"
    rm -rf "$jz_path/dubboMetaData"/*
    log "✅ 已清空目录：$jz_path/dubboMetaData"
    log "基座 jar 启动指令: $jdk_setting -Dlogging.file.path=$jz_path/log -Dcatalina.home=$jz_path -Dlogging.level.root=INFO -Dspring.active.profiles=dev,uat,daily -Duser.home=$jz_path/dubboMetaData -jar $jz_jar_path"
    $jdk_setting -Dlogging.file.path=$jz_path/log -Dcatalina.home=$jz_path -Dlogging.level.root=INFO -Dspring.active.profiles=dev -Duser.home=$jz_path/dubboMetaData -jar "$jz_jar_path"
    log "✅ 启动完成"
}

# 主流程
main() {
    clear
    if [ ! -f "$clone_config_file" ]; then
        echo "错误：ops文件不存在。终止运行。"
        exit 1
    fi

    build_type=""
    run_type=""
    project_names=""

    if [[ "$#" -eq 0 ]]; then
        build_type="yes"
        run_type="yes"
    fi

    while [[ "$1" != "" ]]; do
        case $1 in
            -r)
                run_type="yes"
                shift
                ;;
            -b)
                build_type="yes"
                shift
                if [[ -n "$1" && "$1" != "-"* ]]; then
                    project_names="$1"
                    shift
                fi
                ;;
           -br)
                run_type="yes"
                build_type="yes"
                shift
                 if [[ -n "$1" && "$1" != "-"* ]]; then
                      project_names="$1"
                      shift
                  fi
                ;;
            --help)
                show_help
                exit 0
                ;;
            *)
                echo "无效的选项: $1"
                show_help
                exit 1
                ;;
        esac
    done

    if [[ "$build_type" == "yes" ]]; then
        IFS=',' read -ra project_array <<< "${project_names:-$(ls -d */ | grep -v '^hs_koupleless/' | sed 's:/$::' | paste -sd, -)}"
        project_paths=()
        jz_path=""
        parent_dir=""
        for proj in "${project_array[@]}"; do
            proj_path=$(read_config "project.plugin.$proj.baseProject")
            if [[ ! -d "$proj_path" ]]; then
                log "❌ 项目目录 $proj_path 不存在，终止执行"
                exit 1
            fi
            parent_dir="$proj_path"
            if [[ -z "$jz_path" ]]; then
                jz_path=$(read_config "project.plugin.jz.$proj_path.path")
                if [[ -z "$jz_path" ]]; then
                    log "❌ $clone_config_file 未找到配置项 project.plugin.jz.$proj_path.path 终止"
                    exit 1
                fi
            fi

            project_paths+=("$proj")
        done
        build_projects "${project_paths[@]}" "$jz_path" "$parent_dir"
    fi
    [[ "$run_type" == "yes" ]] && run_projects
}

main "$@"
